package com.cf.base.comm.tools;


import android.app.Activity;

import androidx.annotation.NonNull;

import com.cf.base.comm.callback.ActivityLifecycleCallbacks;

/**
 * APP 是否处于后台跟踪
 *
 * @author yangji
 */
public class VisibilityTracker extends ActivityLifecycleCallbacks {

    /**
     * App 是否处于可见（是否后台）
     */
    public interface OnVisibilityListener {
        /**
         * App 是否处于可见
         *
         * @param isVisibility true 可见，false 后台
         */
        void onVisibility(boolean isVisibility);
    }

    /**
     * 已显示 Activity 数量
     */
    private int startedActivityCount = 0;

    private boolean hasVisibleActivities = false;

    private OnVisibilityListener listener;

    public void setListener(OnVisibilityListener listener) {
        this.listener = listener;
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {
        super.onActivityStarted(activity);
        startedActivityCount++;
        if (!hasVisibleActivities && startedActivityCount == 1) {
            hasVisibleActivities = true;
            if (listener != null) {
                listener.onVisibility(true);
            }
        }
    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {
        super.onActivityStopped(activity);
        if (startedActivityCount > 0) {
            startedActivityCount--;
        }
        if (hasVisibleActivities && startedActivityCount == 0 && !activity.isChangingConfigurations()) {
            hasVisibleActivities = false;
            if (listener != null) {
                listener.onVisibility(false);
            }
        }
    }
}
